from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from .models import UserCaptcha, UserInfo
from .captcha import gen_captcha
from django.utils import timezone
from music_lzz.settings import EMAIL_CAPTCHA

User = get_user_model()

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=20)
    password = serializers.CharField(max_length=16)

class UserCreateSerailizer(serializers.ModelSerializer):

    def validate(self, attrs):
        attrs['password'] = make_password(attrs['password'])
        email = attrs['email']
        captcha = attrs['captcha']
        validation_time = timezone.now() - timezone.timedelta(seconds=60)
        res = UserCaptcha.objects.filter(email=email, captcha=captcha, add_time__gte=validation_time).exists()
        if not res:
            raise serializers.ValidationError({'error': '验证码错误或失效'})
        del(attrs['captcha'])
        return super().validate(attrs)

    class Meta:
        model = User
        fields = ('username', 'password', 'email', 'captcha')


class UserCaptchaCreateSerializer(serializers.ModelSerializer):

    def validate(self, attrs):
        email = attrs['email']
        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError('邮箱已经存在')
        #发送时间间隔的限制
        expire_time = timezone.now() - timezone.timedelta(seconds=EMAIL_CAPTCHA['delay_time']['register'])
        if UserCaptcha.objects.filter(email=email, add_time__gte=expire_time).exists():
            raise serializers.ValidationError({'error': '请稍后再发送请求验证码'})
        captcha = gen_captcha()
        attrs['captcha'] = captcha
        return super().validate(attrs)

    class Meta:
        model = UserCaptcha
        fields = ('email',)



